package com.example.autocall2;

import android.annotation.SuppressLint;
import android.app.Service;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.IBinder;
import android.provider.CallLog.Calls;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;

import java.lang.reflect.Method;

public class AutoRedialService extends Service {
	private int mRetryCount = 0;
	private int mDialedCount = 0;
	private String mPhoneNumber = "10086";
	private boolean mJustCall = false;

	@Override
	public IBinder onBind(Intent msg) {
		return null;
	}

	private void PhoneCall() {
		try {
			Thread.sleep(2000);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		mJustCall = false;
		Uri localUri = Uri.parse("tel:" + mPhoneNumber);
		Intent call = new Intent(Intent.ACTION_CALL, localUri);
		call.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		startActivity(call);
		mDialedCount++;
	}

	private boolean ShouldStop() {
		return mDialedCount >= mRetryCount;
	}

	private boolean LastCallSucceed() {
		if (!mJustCall) {
			return false;
		}
		String[] projection = new String[] { Calls.NUMBER, Calls.DURATION };
		ContentResolver cr = getContentResolver();
		final Cursor cur = cr.query(Calls.CONTENT_URI,
				projection, null, null, Calls.DEFAULT_SORT_ORDER);
		if (cur.moveToFirst()) {
			int duration = cur.getInt(1);
			// 上次通话时间
			return duration > 0;
		}
		return false;
	}

	public void onCreate() {
		super.onCreate();
	}

	@SuppressWarnings("deprecation")
	public void onStart(Intent intent, int startID) {
		super.onStart(intent, startID);
		// 获取电话管理的一个类实例
		mRetryCount = intent.getIntExtra("RetryCount", 0);
		String tmp = intent.getStringExtra("PhoneNumber");
		if (tmp != null) {
			mPhoneNumber = tmp;
		}
		TelephonyManager telephonyMgr = (TelephonyManager) this
				.getSystemService(Context.TELEPHONY_SERVICE);
		// 建立一个监听器来实时监听电话的通话状态
		telephonyMgr.listen(new TeleListener(this),
				PhoneStateListener.LISTEN_CALL_STATE);
		mDialedCount = 0;
		// PhoneCall();
	}

	public void onDestroy() {
		@SuppressLint("WrongConstant") TelephonyManager telephonyMgr = (TelephonyManager) getSystemService("phone");
		TeleListener teleListener = new TeleListener(this);
		telephonyMgr.listen(teleListener, 0);
		mDialedCount = 0;
		mRetryCount = 0;
		mPhoneNumber = "10086";
		super.onDestroy();
	}

	class TeleListener extends PhoneStateListener {
		private AutoRedialService manager;

		public TeleListener(AutoRedialService a) {
			this.manager = a;
		}

		@Override
		public void onCallStateChanged(int state, String incomingNumber) {
			super.onCallStateChanged(state, incomingNumber);
			switch (state) {
			// 无任何状态时
			case TelephonyManager.CALL_STATE_IDLE: {
				Log.d("TAG","IDLE");
				if (manager.ShouldStop()) {
					manager.stopSelf();
					break;
				}
				PhoneCall();
				break;
			}
			// 接起电话时
			case TelephonyManager.CALL_STATE_OFFHOOK: {
				Log.d("TAG","OFFHOOK");
				mJustCall = true;
				break;
			}
//			电话进来时
			case TelephonyManager.CALL_STATE_RINGING: {
				Log.d("TAG","RINGING");
				break;
			}
			default:
				break;
			}
		}
	}
	//挂断电话
	public static void endCall(Context cx) {
		TelephonyManager telMag = (TelephonyManager) cx
				.getSystemService(Context.TELEPHONY_SERVICE);
		Class<TelephonyManager> c = TelephonyManager.class;
		Method mthEndCall = null;
		try {
			mthEndCall = c.getDeclaredMethod("getITelephony", (Class[]) null);
			mthEndCall.setAccessible(true);
			ITelephony iTel = (ITelephony) mthEndCall.invoke(telMag,
					(Object[]) null);
			assert iTel != null;
			iTel.endCall();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

}